//
//  TextViewWithPlaceholder.m
//  digital_robot_demo
//
//  Created by xskj on 2024/9/20.
//

#import "TextViewWithPlaceholder.h"

@interface TextViewWithPlaceholder()

@end

@implementation TextViewWithPlaceholder

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.placeholderLabel = [[UILabel alloc] initWithFrame:self.bounds];
        self.placeholderLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        self.placeholderLabel.numberOfLines = 0;
        [self addSubview:self.placeholderLabel];
        
        [self setupObservers];
    }
    return self;
}
 
- (void)setupObservers {
    // KVO to observe text changes
    [self addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:nil];
}
 
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"text"]) {
        self.placeholderLabel.hidden = self.text.length > 0;
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
 
- (void)dealloc {
    [self removeObserver:self forKeyPath:@"text"];
}
 
- (void)setPlaceholder:(NSString *)placeholder {
    _placeholder = placeholder;
    self.placeholderLabel.textColor = COLOR_TextGray88;
    self.placeholderLabel.text = placeholder;
}
 
- (void)setText:(NSString *)text {
    [super setText:text];
    self.placeholderLabel.hidden = text.length > 0;
}

@end
